/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.databox.synchronizeselection;

import java.awt.BorderLayout;
import java.util.Iterator;

import javax.swing.JFrame;
import javax.swing.JScrollPane;

import twaver.DataBoxSelectionEvent;
import twaver.DataBoxSelectionListener;
import twaver.Element;
import twaver.TDataBox;
import twaver.Node;
import twaver.network.TNetwork;
import twaver.tree.TTree;

public class SynchronizeSelectionDemo {	
    private TDataBox box1 = new TDataBox(); 
    private TDataBox box2 = new TDataBox(); 
    private TTree tree = new TTree(box1);
    private TNetwork network = new TNetwork(box2);
    private JFrame frame = new JFrame();
    private boolean isSynchronizing = false;
    
	public SynchronizeSelectionDemo(){
		createNode("A", 100);
		createNode("B", 200);
		createNode("C", 300);
		createNode("D", 400);
		createNode("E", 500);
		
		tree.expandAll();
		frame.setTitle("Synchronized Selection Demo");
		frame.getContentPane().setLayout(new BorderLayout());
		frame.getContentPane().add(new JScrollPane(tree), BorderLayout.WEST);
		frame.getContentPane().add(network);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 400);
        frame.setVisible(true);
        
        box1.getSelectionModel().addDataBoxSelectionListener(new DataBoxSelectionListener(){
			public void selectionChanged(DataBoxSelectionEvent e) {
				if(isSynchronizing){
					return;
				}
				isSynchronizing = true;
				box2.getSelectionModel().clearSelection();
				Iterator it = box1.getSelectionModel().getAllSelectedElement().iterator();
				while(it.hasNext()){
					Element element = (Element)it.next();
					box2.getSelectionModel().appendSelection(box2.getElementByID(element.getID())); 
				}
				isSynchronizing = false;
			}
        });
        box2.getSelectionModel().addDataBoxSelectionListener(new DataBoxSelectionListener(){
			public void selectionChanged(DataBoxSelectionEvent e) {
				if(isSynchronizing){
					return;
				}
				isSynchronizing = true;
				box1.getSelectionModel().clearSelection();
				Iterator it = box2.getSelectionModel().getAllSelectedElement().iterator();
				while(it.hasNext()){
					Element element = (Element)it.next();
					box1.getSelectionModel().appendSelection(box1.getElementByID(element.getID())); 
				}
				isSynchronizing = false;
			}
        });
	}
	
	public void createNode(String name, int x){
		Node node1 = new Node(name);
		node1.setName(name);
		box1.addElement(node1);

		Node node2 = new Node(name);
		node2.setName(name);
		node2.setLocation(x, 100);
		box2.addElement(node2);
	}
	
	public static void main(String[] args) {
		new SynchronizeSelectionDemo(); 
	}
}